package com.sml.utils;


import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Util {

    /**
     * 默认密码字符串组合，用来将字符串转换为16进制字符串。appache校验下载的文件的正确性用的就是使用MD5加密算法和这个字符串组合。
     */
    private static final char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

    protected static MessageDigest md = null;
    static {
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            System.out.println(MD5Util.class.getName() + "初始化失败，MessageDigest不支持MD5Util。");
            e.printStackTrace();
        }
    }

   public static String getMD5String(String s) {
        return getMD5String(s.getBytes());
    }

    private static String getMD5String(byte[] s) {
        byte[] bs = md.digest(s);
        return byteToHexString(bs);
    }

    private static String byteToHexString(byte[] bs) {
        char[] digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
        char[] chs = new char[32];
        for (int i = 0; i < bs.length; i++) {
            chs[i * 2] = digit[(bs[i] >>> 4) & 0x0f];
            chs[i * 2 + 1] = digit[bs[i] & 0x0f];
            System.out.println(chs[i * 2] + " " + chs[i * 2 + 1]);
        }
        return new String(chs);
    }

    /**
     * 判断字符串的MD5是否和标准MD5相等
     * @param password  要校验的字符串
     * @param md5PwdStr 标准的MD5加密后的字符串
     * @return
     */
    public static boolean checkPassword(String password, String md5PwdStr) {
        return md5PwdStr.equals(getMD5String(password));
    }
}
